package com.chart.web.controller.chart;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chart.chart.domian.ChartViewsUser;
import com.chart.chart.domian.vo.ChartViewsVo;
import com.chart.chart.service.IChartViewsUserService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.page.TableDataInfo;
import com.chart.common.utils.SecurityUtils;
import com.chart.framework.config.ServerConfig;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

/**
 * 图表大屏
 *
 * @author chart
 */
@RestController
@RequestMapping("/view/chart")
public class ChartViewsController extends BaseController
{

    @Value("${phtoto.viewPhotoUrl}")
    private String viewPhotoUrl;

    @Value("${phtoto.photoUrl}")
    private String photoUrl;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IChartViewsUserService chartViewsUserService;



    @ApiOperation("数字大屏：列表")
    @GetMapping("/user/list")
    @Transactional
    public TableDataInfo list(ChartViewsVo chartViewsVo)
    {
        chartViewsVo.setUserId(SecurityUtils.getUserId());
        List<ChartViewsVo> list =chartViewsUserService.getList(chartViewsVo);
        return getDataTable(list);
    }


    @ApiOperation("数字大屏：新增")
    @PostMapping("/user/add")
    @Transactional
    public AjaxResult add(@RequestBody ChartViewsUser chartViewsUser)
    {
        if (ObjectUtils.isEmpty(chartViewsUser.getViewName())) {
            return AjaxResult.error("请填写大屏名称");
        }
        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getViewName, chartViewsUser.getViewName())
                .eq(ChartViewsUser::getUserId,SecurityUtils.getUserId()));

        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("大屏名称重复");
        }

        chartViewsUser.setUserId(SecurityUtils.getUserId());
        if (!ObjectUtils.isEmpty(chartViewsUser.getBase64Data())) {
            String base64Image = chartViewsUser.getBase64Data();
            // 将base64编码的图片字符串解码
            String croppedBase64Image = base64Image.substring(base64Image.indexOf(",") + 1);
            byte[] decodedBytes = Base64.getDecoder().decode(croppedBase64Image);

            // 获取图片类型
            String imageType = base64Image.substring(base64Image.indexOf("/") + 1, base64Image.indexOf(";"));
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            String newFileName = viewPhotoUrl+uuid + "." + imageType;

            String photo = photoUrl+uuid + "." + imageType;

            // 将解码后的字节数组保存为图片文件
            try (FileOutputStream fos = new FileOutputStream(newFileName)) {
                fos.write(decodedBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String viewValue = chartViewsUser.getViewValue();
            JSONObject jsonObject = JSON.parseObject(viewValue);
            jsonObject.put("base64Data",photo);
            chartViewsUser.setViewValue(JSON.toJSONString(jsonObject));
        }
        boolean result = chartViewsUserService.save(chartViewsUser);
        if (result) {
            return AjaxResult.success(chartViewsUser.getId());
        }
        return AjaxResult.error();
    }

    @ApiOperation("数字大屏：修改")
    @PostMapping("/user/edit")
    @Transactional
    public AjaxResult edit(@RequestBody ChartViewsUser chartViewsUser,MultipartFile file)
    {
        if (ObjectUtils.isEmpty(chartViewsUser.getViewName())) {
            return AjaxResult.error("请填写图表名称");
        }
        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getViewName, chartViewsUser.getViewName())
                .ne(ChartViewsUser::getId,chartViewsUser.getId()).eq(ChartViewsUser::getUserId,SecurityUtils.getUserId()));
        if (!ObjectUtils.isEmpty(one)) {
            return AjaxResult.error("图表名称重复");
        }
        if (!ObjectUtils.isEmpty(chartViewsUser.getBase64Data())) {
            String base64Image = chartViewsUser.getBase64Data();
            // 将base64编码的图片字符串解码
            byte[] decodedBytes = Base64.getDecoder().decode(base64Image);
            // 获取图片类型
            String imageType = base64Image.substring(base64Image.indexOf("/") + 1, base64Image.indexOf(";"));

            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            String newFileName = viewPhotoUrl+uuid + "." + imageType;

            String photo = photoUrl+uuid + "." + imageType;

            // 将解码后的字节数组保存为图片文件
            try (FileOutputStream fos = new FileOutputStream(newFileName)) {
                fos.write(decodedBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String viewValue = chartViewsUser.getViewValue();
            JSONObject jsonObject = JSON.parseObject(viewValue);
            jsonObject.put("base64Data",photo);
            chartViewsUser.setViewValue(JSON.toJSONString(jsonObject));
        }
        return AjaxResult.success(chartViewsUserService.saveOrUpdate(chartViewsUser));
    }


    @ApiOperation("数字大屏：根据id获取单个图表详情")
    @GetMapping("/user/getInfo")
    public AjaxResult getInfo(ChartViewsUser chartViewsUser)
    {
        ChartViewsUser one = chartViewsUserService.getOne(new LambdaQueryWrapper<ChartViewsUser>().eq(ChartViewsUser::getId, chartViewsUser.getId()));
        return AjaxResult.success(one);
    }

    @ApiOperation("数字大屏：根据id删除（支持批量）")
    @PostMapping("/user/del")
    @Transactional
    public AjaxResult del(@RequestBody ChartViewsUser chartViewsUser)
    {
        return AjaxResult.success(chartViewsUserService.removeByIds(chartViewsUser.getIds()));
    }

}
